package com.sys.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CharsetFilter implements Filter {

    private String charset ;
    private List<String> nofilters = new ArrayList<>();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        charset = filterConfig.getInitParameter("charset");
        String nofilter = filterConfig.getInitParameter("nofilter");
        String[] arr = nofilter.split(",");
        Collections.addAll(nofilters,arr);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(charset == null || "".equals(charset)){
            throw new RuntimeException("请设置charset！");
        }
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        boolean b = isNotFilter(req);

        if(b) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        servletRequest.setCharacterEncoding(charset);
        // 向浏览器发送文字不乱吗
        servletResponse.setContentType("text/html; charset=" + charset);

        // 必须调用下面代码，否则程序不在往下执行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private boolean isNotFilter(HttpServletRequest req) {

        String servletPath = req.getServletPath();
        for (String nofilter : nofilters){
            nofilter=nofilter.replaceAll("\\.", "\\\\.");
            nofilter=nofilter.replaceAll("\\*", "\\.\\*");//将*替换成.*，然后进行正则表达式匹配
            if(servletPath.matches(nofilter)){
                return true;
            }
        }
        return false;
    }


    @Override
    public void destroy() {
        System.out.println(this.getClass().getSimpleName()+"的destroy() 方法");

    }
}
